<template>
  <div class="auto-template-demo">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1>{{ projectConfig.projectName }} - 原始记录模板</h1>
      <div class="project-info">
        <el-tag type="primary">标准: {{ projectConfig.standardCode }}</el-tag>
        <el-tag>项目ID: {{ projectConfig.projectId }}</el-tag>
        <el-tag type="info">描述: {{ projectConfig.description }}</el-tag>
      </div>
    </div>

    <!-- 模板内容 -->
    <div class="template-content">
      <!-- 固定页眉 -->
      <div class="template-header">
        <div class="header-main">
          <h2>检测原始记录</h2>
          <div class="header-details">
            <p>项目名称: {{ projectConfig.projectName }}</p>
            <p>检测标准: {{ projectConfig.standardCode }}</p>
          </div>
        </div>
      </div>

      <!-- 参数区域 -->
      <div class="parameters-area">
        <!-- 遍历参数组 -->
        <div
          v-for="group in sortedParamGroups"
          :key="group.groupId"
          class="parameter-group-container"
        >
          <!-- 普通参数组 -->
          <static-parameter-group
            v-if="!group.isNested && !group.allowDynamicRows"
            :group="group"
            :form-data="formData"
            @param-change="handleParamChange"
          />

          <!-- 嵌套参数组 -->
          <nested-parameter-group
            v-else-if="group.isNested"
            :group="group"
            :form-data="formData"
            @param-change="handleParamChange"
          />

          <!-- 动态表格参数组 -->
          <dynamic-table-group
            v-else-if="group.allowDynamicRows"
            :group="group"
            :table-data="tableData"
            @table-change="handleTableChange"
          />
        </div>
      </div>

      <!-- 固定页脚 -->
      <div class="template-footer">
        <div class="signature-section">
          <div class="signature-line">
            <span class="label">检测人:</span>
            <div class="signature-field"></div>
            <span class="label">日期:</span>
            <div class="date-field">{{ currentDate }}</div>
          </div>
          <div class="signature-line">
            <span class="label">审核人:</span>
            <div class="signature-field"></div>
            <span class="label">日期:</span>
            <div class="date-field"></div>
          </div>
        </div>
      </div>
    </div>

    <!-- 操作工具栏 -->
    <div class="action-toolbar">
      <el-button type="primary" @click="saveData" icon="el-icon-document">
        保存数据
      </el-button>
      <el-button @click="resetData" icon="el-icon-refresh">
        重置数据
      </el-button>
      <el-button @click="exportData" icon="el-icon-download">
        导出记录
      </el-button>
      <el-button type="success" @click="validateData" icon="el-icon-check">
        验证数据
      </el-button>
    </div>

    <!-- 数据预览面板 -->
    <div class="data-preview">
      <h3>数据预览</h3>
      <pre>{{ JSON.stringify({ formData, tableData, calculatedValues }, null, 2) }}</pre>
    </div>
  </div>
</template>

<script>
import StaticParameterGroup from '@/components/StaticParameterGroup.vue'
import NestedParameterGroup from '@/components/NestedParameterGroup.vue'
import DynamicTableGroup from '@/components/DynamicTableGroup.vue'

// 项目配置数据
const projectConfig = {
  "projectId": "2",
  "projectName": "测试数据1",
  "standardCode": "GB/T 50081-2019",
  "description": "测试1",
  "paramGroups": [
    {
      "groupId": "GRPx27wNQ_0",
      "groupName": "参数组1",
      "isNested": false,
      "allowDynamicRows": false,
      "maxRows": 3,
      "sortOrder": 2,
      "childGroups": [],
      "paramItems": [
        {
          "paramId": "PARAMkpglYW5V",
          "paramName": "新参数1",
          "paramCode": "a_ui8b",
          "dataType": "number",
          "paramType": "base",
          "unit": "",
          "required": false,
          "calculationExpr": "",
          "dependencies": [],
          "options": [],
          "validateRule": {
            "min": 1,
            "max": 100,
            "required": true,
            "requiredMsg": "此字段为必填项",
            "rangeMsg": "请输入1到100之间的数"
          },
          "conditionShow": {},
          "precision": 1,
          "columnWidth": 120,
          "placeholder": "",
          "isMultiMeasure": false,
          "multiMeasureCount": 1,
          "sortOrder": 1
        },
        {
          "paramId": "PARAMLQoGTiTn",
          "paramName": "新参数2",
          "paramCode": "a_udfi",
          "dataType": "text",
          "paramType": "base",
          "unit": "",
          "required": false,
          "calculationExpr": "",
          "dependencies": [],
          "options": [],
          "validateRule": {
            "required": true,
            "requiredMsg": "此字段为必填项",
            "regex": "^\\d+$",
            "regexMsg": "此字段只能输入数字"
          },
          "conditionShow": {},
          "precision": 1,
          "columnWidth": 120,
          "placeholder": "",
          "isMultiMeasure": false,
          "multiMeasureCount": 1,
          "sortOrder": 2
        },
        {
          "paramId": "PARAMOOO1UEZb",
          "paramName": "新参数",
          "paramCode": "a_u9bh",
          "dataType": "number",
          "paramType": "calculation",
          "unit": "kp",
          "required": false,
          "calculationExpr": "ROUND(a_ui8b * 1.0, 2)",
          "dependencies": [
            "a_ui8b"
          ],
          "options": [],
          "validateRule": {
            "required": false,
            "requiredMsg": "此字段为必填项",
            "rangeMsg": ""
          },
          "conditionShow": {},
          "precision": 1,
          "columnWidth": 120,
          "placeholder": "",
          "isMultiMeasure": false,
          "multiMeasureCount": 1,
          "sortOrder": 3
        }
      ]
    },
    {
      "groupId": "GRPVr2cDi_1",
      "groupName": "参数组2",
      "isNested": true,
      "allowDynamicRows": false,
      "maxRows": 3,
      "sortOrder": 2,
      "childGroups": [
        {
          "groupId": "CHILDAmy2_0",
          "groupName": "子组1",
          "paramItems": [
            {
              "paramId": "PARAM507QIVU8",
              "paramName": "新参数3",
              "paramCode": "a_xqgx",
              "dataType": "text",
              "paramType": "base",
              "unit": "",
              "required": false,
              "calculationExpr": "",
              "dependencies": [],
              "options": [],
              "validateRule": {},
              "conditionShow": {},
              "precision": 1,
              "columnWidth": 120,
              "placeholder": "",
              "isMultiMeasure": false,
              "multiMeasureCount": 1,
              "sortOrder": 1
            },
            {
              "paramId": "PARAMd8Tp8zYZ",
              "paramName": "新参数4",
              "paramCode": "a_390n",
              "dataType": "text",
              "paramType": "base",
              "unit": "",
              "required": false,
              "calculationExpr": "",
              "dependencies": [],
              "options": [],
              "validateRule": {},
              "conditionShow": {},
              "precision": 1,
              "columnWidth": 120,
              "placeholder": "",
              "isMultiMeasure": false,
              "multiMeasureCount": 1,
              "sortOrder": 2
            }
          ]
        },
        {
          "groupId": "CHILDlQaA_1",
          "groupName": "子组2",
          "paramItems": [
            {
              "paramId": "PARAM5qpzSRdM",
              "paramName": "新参数5",
              "paramCode": "a_4t2t",
              "dataType": "number",
              "paramType": "base",
              "unit": "",
              "required": false,
              "calculationExpr": "",
              "dependencies": [],
              "options": [],
              "validateRule": {},
              "conditionShow": {},
              "precision": 1,
              "columnWidth": 120,
              "placeholder": "",
              "isMultiMeasure": false,
              "multiMeasureCount": 1,
              "sortOrder": 1
            },
            {
              "paramId": "PARAMo5jiZRGW",
              "paramName": "新参数6",
              "paramCode": "a_sc4j",
              "dataType": "number",
              "paramType": "calculation",
              "unit": "",
              "required": false,
              "calculationExpr": "ROUND(a_u9bh * 1.0 + a_4t2t, 2)",
              "dependencies": [
                "a_u9bh",
                "a_4t2t"
              ],
              "options": [],
              "validateRule": {},
              "conditionShow": {},
              "precision": 1,
              "columnWidth": 120,
              "placeholder": "",
              "isMultiMeasure": false,
              "multiMeasureCount": 1,
              "sortOrder": 2
            }
          ]
        }
      ],
      "paramItems": []
    },
    {
      "groupId": "GRPhRV3zJ_2",
      "groupName": "参数组3",
      "isNested": false,
      "allowDynamicRows": true,
      "maxRows": 3,
      "sortOrder": 3,
      "childGroups": [],
      "paramItems": [
        {
          "paramId": "PARAMHPXzBu3J",
          "paramName": "新参数7",
          "paramCode": "a_ddoi",
          "dataType": "number",
          "paramType": "base",
          "unit": "",
          "required": false,
          "calculationExpr": "",
          "dependencies": [],
          "options": [],
          "validateRule": {},
          "conditionShow": {},
          "precision": 1,
          "columnWidth": 180,
          "placeholder": "",
          "isMultiMeasure": true,
          "multiMeasureCount": 3,
          "sortOrder": 1
        },
        {
          "paramId": "PARAMPTn8RUJC",
          "paramName": "新参数8",
          "paramCode": "a_01mv",
          "dataType": "number",
          "paramType": "base",
          "unit": "",
          "required": false,
          "calculationExpr": "",
          "dependencies": [],
          "options": [],
          "validateRule": {},
          "conditionShow": {},
          "precision": 1,
          "columnWidth": 180,
          "placeholder": "",
          "isMultiMeasure": true,
          "multiMeasureCount": 3,
          "sortOrder": 2
        },
        {
          "paramId": "PARAMTrGiCRml",
          "paramName": "新参数9",
          "paramCode": "a_lomi",
          "dataType": "number",
          "paramType": "calculation",
          "unit": "",
          "required": false,
          "calculationExpr": "ROUND(AVG(a_ddoi[0].value, a_ddoi[1].value, a_ddoi[2].value) + AVG(a_01mv[0].value, a_01mv[1].value, a_01mv[2].value), 2)",
          "dependencies": [
            "a_ddoi",
            "a_01mv"
          ],
          "options": [],
          "validateRule": {},
          "conditionShow": {},
          "precision": 1,
          "columnWidth": 120,
          "placeholder": "",
          "isMultiMeasure": false,
          "multiMeasureCount": 1,
          "sortOrder": 3
        },
        {
          "paramId": "PARAM8TCbuwgk",
          "paramName": "新参数10",
          "paramCode": "新参_8t0l",
          "dataType": "text",
          "paramType": "base",
          "unit": "",
          "required": false,
          "calculationExpr": "",
          "dependencies": [],
          "options": [],
          "validateRule": {},
          "conditionShow": {},
          "precision": 1,
          "columnWidth": 120,
          "placeholder": "",
          "isMultiMeasure": false,
          "multiMeasureCount": 1,
          "sortOrder": 4
        }
      ]
    }
  ]
}

export default {
  name: 'AutoTemplateDemo',
  components: {
    StaticParameterGroup,
    NestedParameterGroup,
    DynamicTableGroup
  },
  data() {
    return {
      projectConfig,
      formData: {},
      tableData: {},
      calculatedValues: {},
      validationErrors: {}
    }
  },
  computed: {
    sortedParamGroups() {
      return [...this.projectConfig.paramGroups].sort((a, b) => a.sortOrder - b.sortOrder)
    },
    currentDate() {
      return new Date().toLocaleDateString('zh-CN')
    }
  },
  created() {
    this.initializeData()
  },
  methods: {
    initializeData() {
      // 初始化表单数据
      this.projectConfig.paramGroups.forEach(group => {
        if (group.allowDynamicRows) {
          this.initializeTableData(group)
        } else {
          this.initializeFormData(group)
        }
      })
    },

    initializeFormData(group) {
      group.paramItems.forEach(param => {
        if (param.paramType === 'base') {
          this.$set(this.formData, param.paramCode, this.getDefaultValue(param))
        }
      })

      // 处理嵌套组
      if (group.isNested && group.childGroups) {
        group.childGroups.forEach(childGroup => {
          childGroup.paramItems.forEach(param => {
            if (param.paramType === 'base') {
              this.$set(this.formData, param.paramCode, this.getDefaultValue(param))
            }
          })
        })
      }
    },

    initializeTableData(group) {
      const tableRows = []
      const rowCount = group.maxRows || 3

      for (let i = 0; i < rowCount; i++) {
        const row = {}
        group.paramItems.forEach(param => {
          if (param.isMultiMeasure) {
            // 多测次参数
            const measures = []
            for (let j = 0; j < param.multiMeasureCount; j++) {
              measures.push(this.getDefaultValue(param))
            }
            row[param.paramCode] = measures
          } else {
            row[param.paramCode] = this.getDefaultValue(param)
          }
        })
        tableRows.push(row)
      }

      this.$set(this.tableData, group.groupId, tableRows)
    },

    getDefaultValue(param) {
      switch (param.dataType) {
        case 'number':
          return 0
        case 'text':
          return ''
        default:
          return ''
      }
    },

    handleParamChange({ paramCode, value }) {
      this.$set(this.formData, paramCode, value)
      this.updateCalculatedParams(paramCode)
    },

    handleTableChange({ groupId, rowIndex, paramCode, value }) {
      if (!this.tableData[groupId]) return
      this.$set(this.tableData[groupId][rowIndex], paramCode, value)
      this.updateTableCalculatedParams(groupId, paramCode)
    },

    updateCalculatedParams(changedParamCode) {
      this.projectConfig.paramGroups.forEach(group => {
        group.paramItems.forEach(param => {
          if (param.paramType === 'calculation' && 
              param.dependencies.includes(changedParamCode)) {
            this.calculateParamValue(param)
          }
        })

        // 处理嵌套组的计算参数
        if (group.childGroups) {
          group.childGroups.forEach(childGroup => {
            childGroup.paramItems.forEach(param => {
              if (param.paramType === 'calculation' && 
                  param.dependencies.includes(changedParamCode)) {
                this.calculateParamValue(param)
              }
            })
          })
        }
      })
    },

    updateTableCalculatedParams(groupId, changedParamCode) {
      const group = this.projectConfig.paramGroups.find(g => g.groupId === groupId)
      if (!group) return

      group.paramItems.forEach(param => {
        if (param.paramType === 'calculation' && 
            param.dependencies.includes(changedParamCode)) {
          this.calculateTableParam(groupId, param)
        }
      })
    },

    calculateParamValue(param) {
      try {
        const context = this.buildCalculationContext()
        const value = this.evaluateCalculation(param.calculationExpr, context, param.precision)
        this.$set(this.formData, param.paramCode, value)
        this.$set(this.calculatedValues, param.paramCode, value)
      } catch (error) {
        console.error(`计算参数 ${param.paramName} 失败:`, error)
        this.$set(this.formData, param.paramCode, '计算错误')
      }
    },

    calculateTableParam(groupId, param) {
      try {
        const tableRows = this.tableData[groupId]
        if (!tableRows) return

        tableRows.forEach((row, index) => {
          const context = this.buildTableCalculationContext(groupId, index)
          const value = this.evaluateCalculation(param.calculationExpr, context, param.precision)
          this.$set(row, param.paramCode, value)
        })
      } catch (error) {
        console.error(`计算表格参数 ${param.paramName} 失败:`, error)
      }
    },

    buildCalculationContext() {
      const context = { ...this.formData }
      
      // 添加数学函数
      context.ROUND = (value, precision) => {
        const factor = Math.pow(10, precision)
        return Math.round(value * factor) / factor
      }
      
      context.AVG = (...args) => {
        const values = args.flat().filter(v => typeof v === 'number')
        return values.length > 0 ? values.reduce((sum, v) => sum + v, 0) / values.length : 0
      }
      
      return context
    },

    buildTableCalculationContext(groupId, rowIndex) {
      const row = this.tableData[groupId][rowIndex]
      const context = { ...row }
      
      context.ROUND = (value, precision) => {
        const factor = Math.pow(10, precision)
        return Math.round(value * factor) / factor
      }
      
      context.AVG = (...args) => {
        const values = args.flat().filter(v => typeof v === 'number')
        return values.length > 0 ? values.reduce((sum, v) => sum + v, 0) / values.length : 0
      }
      
      return context
    },

    evaluateCalculation(expr, context, precision) {
      try {
        // 替换参数名为上下文中的值
        let safeExpr = expr
        Object.keys(context).forEach(key => {
          const regex = new RegExp(`\\b${key}\\b`, 'g')
          safeExpr = safeExpr.replace(regex, `context['${key}']`)
        })

        // 执行计算
        const result = new Function('context', `return ${safeExpr}`)(context)
        
        // 应用精度
        if (precision !== undefined && typeof result === 'number') {
          const factor = Math.pow(10, precision)
          return Math.round(result * factor) / factor
        }
        
        return result
      } catch (error) {
        throw new Error(`表达式计算错误: ${expr}`)
      }
    },

    saveData() {
      const dataToSave = {
        projectId: this.projectConfig.projectId,
        formData: this.formData,
        tableData: this.tableData,
        calculatedValues: this.calculatedValues,
        savedAt: new Date().toISOString()
      }
      
      console.log('保存的数据:', dataToSave)
      this.$message.success('数据保存成功')
    },

    resetData() {
      this.formData = {}
      this.tableData = {}
      this.calculatedValues = {}
      this.initializeData()
      this.$message.info('数据已重置')
    },

    exportData() {
      const dataToExport = {
        project: this.projectConfig.projectName,
        standard: this.projectConfig.standardCode,
        data: {
          formData: this.formData,
          tableData: this.tableData,
          calculatedValues: this.calculatedValues
        },
        exportedAt: new Date().toISOString()
      }
      
      const dataStr = JSON.stringify(dataToExport, null, 2)
      const dataBlob = new Blob([dataStr], { type: 'application/json' })
      const url = URL.createObjectURL(dataBlob)
      const link = document.createElement('a')
      link.href = url
      link.download = `${this.projectConfig.projectName}_记录_${new Date().getTime()}.json`
      link.click()
      URL.revokeObjectURL(url)
      
      this.$message.success('数据导出成功')
    },

    validateData() {
      this.validationErrors = {}
      let hasErrors = false

      // 验证所有参数
      this.projectConfig.paramGroups.forEach(group => {
        group.paramItems.forEach(param => {
          if (param.validateRule && param.validateRule.required && !this.formData[param.paramCode]) {
            this.$set(this.validationErrors, param.paramCode, param.validateRule.requiredMsg)
            hasErrors = true
          }
        })
      })

      if (hasErrors) {
        this.$message.error('数据验证失败，请检查必填字段')
      } else {
        this.$message.success('数据验证通过')
      }
    }
  }
}
</script>

<style scoped>
.auto-template-demo {
  padding: 20px;
  background: #f5f7fa;
  min-height: 100vh;
  font-family: 'Microsoft YaHei', sans-serif;
}

.page-header {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.page-header h1 {
  margin: 0 0 15px 0;
  color: #303133;
  font-size: 24px;
  border-bottom: 2px solid #409eff;
  padding-bottom: 10px;
}

.project-info {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.template-content {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
  overflow: hidden;
}

.template-header {
  background: linear-gradient(135deg, #f0f9ff 0%, #e6f7ff 100%);
  padding: 25px 30px;
  border-bottom: 2px solid #409eff;
}

.header-main h2 {
  margin: 0 0 15px 0;
  color: #303133;
  font-size: 20px;
  text-align: center;
}

.header-details {
  display: flex;
  justify-content: space-around;
  color: #606266;
  font-size: 14px;
}

.parameters-area {
  padding: 0;
}

.parameter-group-container {
  border-bottom: 1px solid #e6e8eb;
}

.parameter-group-container:last-child {
  border-bottom: none;
}

.template-footer {
  padding: 25px 30px;
  background: #f8f9fa;
  border-top: 1px solid #e6e8eb;
}

.signature-section {
  display: flex;
  justify-content: space-between;
  gap: 40px;
}

.signature-line {
  display: flex;
  align-items: center;
  gap: 10px;
  flex: 1;
}

.signature-line .label {
  color: #606266;
  font-weight: 500;
  min-width: 60px;
}

.signature-field {
  flex: 1;
  height: 1px;
  border-bottom: 1px solid #303133;
  margin: 0 10px;
}

.date-field {
  color: #606266;
  min-width: 100px;
  text-align: center;
}

.action-toolbar {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  text-align: center;
  margin-bottom: 20px;
}

.action-toolbar .el-button {
  margin: 0 10px;
}

.data-preview {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.data-preview h3 {
  margin: 0 0 15px 0;
  color: #303133;
  border-bottom: 1px solid #e6e8eb;
  padding-bottom: 10px;
}

.data-preview pre {
  background: #f8f9fa;
  padding: 15px;
  border-radius: 4px;
  overflow-x: auto;
  font-size: 12px;
  line-height: 1.4;
  max-height: 300px;
  overflow-y: auto;
}
</style>